package com.iyundao.io.controller;

/**
 * Created by black on 2019/4/16.
 */

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.iyundao.io.tools.AliyunSmsUtil;
import com.iyundao.io.tools.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

/**
 * 阿里云的短信相关的API
 */
@RestController
@RequestMapping(value = "/api/aliyun")
public class AliyunSmsApiController {

    @Autowired
    private AliyunSmsUtil aliyunSmsUtil;

    @ApiOperation(value = "发送验证码", notes = "发送验证码")
    @RequestMapping(value = "/sendMsg", method = {RequestMethod.POST, RequestMethod.GET}, produces = {"application/json;charset=UTF-8"})
    public ResponseData sendMsg(@RequestBody String params) {

        JSONObject object = JSONObject.parseObject(params);
        String phone = (String) object.get("phone");

        String msgCode = getMsgCode();
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        SmsSingleSenderResult smsSingleSenderResult = sendMsgCode(phone,msgCode);

        stringObjectHashMap.put("info",smsSingleSenderResult);
        stringObjectHashMap.put("code",msgCode);
        return new ResponseData(200,"成功",stringObjectHashMap);
    }



    public SmsSingleSenderResult sendMsgCode(String tnum,String msgCode) {
        // 短信应用 SDK AppID
        int appid = 1400207538;

        // 短信应用 SDK AppKey
        String appkey = "7e09989bfce86b46d2c976219fba6998";

        // 需要发送短信的手机号码
        //String[] phoneNumbers = {tnum};
        //String phoneNumber = "13938984537";
        String phoneNumbers = tnum;

        //System.out.println(phoneNumber);
        System.out.println(phoneNumbers);

        // 短信模板 ID，需要在短信应用中申请
        int templateId = 326896;

        // 签名
        String smsSign = "雷甸党员积分红管家";

        try {
            /*String[] param = {"5678"};
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                    templateId, param, smsSign, "", "");
            System.out.println(result);
            return result;*/
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.send(0, "86", phoneNumbers,
                    "您的验证码：" + msgCode + "，您正进行身份验证，请勿泄露于他人！", "", "");
            System.out.println(result);
            return result;
        } catch (HTTPException e) {
            // HTTP 响应码错误
            e.printStackTrace();
            return new SmsSingleSenderResult();
        } catch (JSONException e) {
            // JSON 解析错误
            e.printStackTrace();
            return new SmsSingleSenderResult();
        } catch (IOException e) {
            // 网络 IO 错误
            e.printStackTrace();
            return new SmsSingleSenderResult();
        }
    }

    private JSONObject sendMsgCode(String tnum){
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSmsUtil.getRegionId(), aliyunSmsUtil.getAccessKeyId(), aliyunSmsUtil.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);

        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", tnum);
        request.putQueryParameter("SignName", "味道山乡");
        request.putQueryParameter("TemplateCode", "SMS_158943745");
        String msgCode = getMsgCode();
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + msgCode + "\"}");

        JSONObject respJson = new JSONObject();
        respJson.put("number",tnum);
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject json = JSONObject.parseObject(response.getData());
            respJson.put("Code",json.get("Code"));
            if(json.get("Code").equals("OK")){
                respJson.put("mag", msgCode);
            }else{
                respJson.put("mag", response.getData());
            }
        } catch (ServerException e) {
            e.printStackTrace();
            respJson.put("Code","fail");
            respJson.put("mag", e.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
            respJson.put("Code","fail");
            respJson.put("mag", e.getMessage());
        }
        return respJson;
    }

    private static String getMsgCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }
}
